<template>
  <div class="max-w-6xl mx-auto p-6 min-h-screen bg-gradient-to-br from-slate-50 to-emerald-50">
    <!-- 页面标题 -->
    <div class="text-center mb-8 p-8 bg-white rounded-2xl shadow-lg">
      <h2 class="flex items-center justify-center gap-3 text-3xl font-semibold text-gray-800 mb-2">
        <n-icon class="text-4xl text-emerald-500" :component="PersonIcon" />
        学生信息编辑
      </h2>
      <p class="text-gray-600">请完善学生的详细信息</p>
    </div>

    <!-- 提示信息模块 -->
    <div class="mb-6 bg-gradient-to-r from-emerald-50 to-green-50 border border-emerald-200 rounded-2xl p-6 shadow-sm">
      <div class="flex items-center gap-3 mb-4">
        <n-icon class="text-2xl text-emerald-600" :component="InfoIcon" />
        <h3 class="text-lg font-semibold text-emerald-800">重要提示信息</h3>
      </div>
      <div class="space-y-2">
        <div v-for="(tip, index) in tipMessages" :key="index" class="flex items-start gap-3 text-sm text-emerald-700">
          <div class="flex-shrink-0 w-1.5 h-1.5 bg-emerald-500 rounded-full mt-2"></div>
          <span>{{ tip }}</span>
        </div>
      </div>
    </div>

    <!-- 基本信息卡片 -->
    <n-card class="mb-6 rounded-2xl border-0 shadow-lg bg-white overflow-hidden" title="" :bordered="false">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3 py-2">
            <n-icon class="text-xl text-emerald-500" :component="UserIcon" />
            <span class="text-lg font-semibold text-gray-800">基本信息</span>
          </div>
          <n-button 
            type="primary" 
            @click="saveBasicInfo"
            :loading="basicInfoLoading"
            :disabled="!basicInfoChanged"
            class="rounded-lg"
          >
            <template #icon>
              <n-icon :component="SaveIcon" />
            </template>
            保存基本信息
          </n-button>
        </div>
      </template>
      
      <n-form ref="basicFormRef" :model="basicInfo" label-placement="top" label-align="left" label-width="auto">
        <n-grid :cols="24" :x-gap="24" :y-gap="5">
          <!-- 第一行：姓名、性别 -->
          <n-form-item-gi :span="12" label="姓名" path="memberName">
            <n-input 
              v-model:value="basicInfo.memberName" 
              placeholder="请输入姓名"
              class="rounded-lg"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="性别" path="genderType">
            <n-select 
              v-model:value="basicInfo.genderType" 
              :options="[{label: '男', value: '男'}, {label: '女', value: '女'}]"
              placeholder="选择性别"
              class="rounded-lg"
            />
          </n-form-item-gi>

          <!-- 第二行：民族、学号 -->
          <n-form-item-gi :span="12" label="民族" path="nationalityDesc">
            <n-input 
              v-model:value="basicInfo.nationalityDesc" 
              placeholder="请输入民族"
              class="rounded-lg"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="学号" path="studentId">
            <n-input 
              v-model:value="basicInfo.studentId" 
              placeholder="请输入学号"
              class="rounded-lg"
            />
          </n-form-item-gi>

          <!-- 第三行：身份证号 -->
          <n-form-item-gi :span="24" label="身份证号" path="idCardNumber">
            <n-input 
              v-model:value="basicInfo.idCardNumber" 
              placeholder="请输入身份证号"
              class="rounded-lg"
            />
          </n-form-item-gi>
          
          <!-- 第四行：班级、专业 -->
          <n-form-item-gi :span="12" label="班级" path="studentClass">
            <n-input 
              v-model:value="basicInfo.studentClass" 
              placeholder="请输入班级"
              class="rounded-lg"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="专业" path="majorField">
            <n-input 
              v-model:value="basicInfo.majorField" 
              placeholder="请输入专业"
              class="rounded-lg"
            />
          </n-form-item-gi>
          
          <!-- 第五行：出生日期、入学年月 -->
          <n-form-item-gi :span="12" label="出生日期" path="birthDate">
            <n-date-picker 
              v-model:formatted-value="basicInfo.birthDate" 
              type="date" 
              value-format="yyyy-MM-dd" 
              style="width: 100%" 
              placeholder="选择出生日期"
              class="rounded-lg"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="入学年月" path="enrollmentDate">
            <n-date-picker 
              v-model:formatted-value="basicInfo.enrollmentDate" 
              type="date" 
              value-format="yyyy-MM-dd" 
              style="width: 100%" 
              placeholder="选择入学日期"
              class="rounded-lg"
            />
          </n-form-item-gi>
          
          <!-- 第六行：毕业年月、手机号 -->
          <n-form-item-gi :span="12" label="毕业年月" path="graduationDate">
            <n-date-picker 
              v-model:formatted-value="basicInfo.graduationDate" 
              type="date" 
              value-format="yyyy-MM-dd" 
              style="width: 100%" 
              placeholder="选择毕业日期"
              class="rounded-lg"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="手机号" path="phoneNumber">
            <n-input 
              v-model:value="basicInfo.phoneNumber" 
              placeholder="请输入手机号"
              class="rounded-lg"
            />
          </n-form-item-gi>
          
          <!-- 第七行：QQ号、入团时间 -->
          <n-form-item-gi :span="12" label="QQ号" path="qqNumber">
            <n-input 
              v-model:value="basicInfo.qqNumber" 
              placeholder="请输入QQ号"
              class="rounded-lg"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="入团时间" path="joinLeagueDate">
            <n-date-picker 
              v-model:formatted-value="basicInfo.joinLeagueDate" 
              type="date" 
              value-format="yyyy-MM-dd" 
              style="width: 100%" 
              placeholder="选择入团时间"
              class="rounded-lg"
            />
          </n-form-item-gi>
          
          <!-- 第八行：政治面貌、当前所在党支部 -->
          <n-form-item-gi :span="12" label="政治面貌" path="politicalStatus">
            <n-input 
              v-model:value="basicInfo.politicalStatus" 
              placeholder="请输入政治面貌"
              class="rounded-lg"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="当前所在党支部" path="currentPartyBranch">
            <n-input 
              v-model:value="basicInfo.currentPartyBranch" 
              placeholder="请输入党支部名称"
              class="rounded-lg"
            />
          </n-form-item-gi>

          <!-- 第九行：籍贯、户口所在地 -->
          <n-form-item-gi :span="12" label="籍贯" path="birthPlace">
            <n-input 
              v-model:value="basicInfo.birthPlace" 
              placeholder="请输入籍贯"
              class="rounded-lg"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="户口所在地" path="residenceLocation">
            <n-input 
              v-model:value="basicInfo.residenceLocation" 
              placeholder="请输入户口所在地"
              class="rounded-lg"
            />
          </n-form-item-gi>

          <!-- 第十行：备注 -->
          <n-form-item-gi :span="24" label="备注" path="memberRemarks">
            <n-input 
              type="textarea" 
              v-model:value="basicInfo.memberRemarks" 
              placeholder="请输入备注信息"
              :autosize="{ minRows: 3, maxRows: 5 }"
              class="rounded-lg"
            />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </n-card>

    <!-- 党支部历史情况卡片 -->
    <n-card class="mb-6 rounded-2xl border-0 shadow-lg bg-white overflow-hidden" title="" :bordered="false">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3 py-2">
            <n-icon class="text-xl text-emerald-600" :component="TeamIcon" />
            <span class="text-lg font-semibold text-gray-800">党支部历史情况</span>
          </div>
          <n-button 
            type="primary" 
            @click="addPartyBranchHistory"
            class="rounded-lg"
            ghost
          >
            <template #icon>
              <n-icon :component="PlusIcon" />
            </template>
            新增党支部历史
          </n-button>
        </div>
      </template>

      <div class="mb-3">
        <n-empty 
          v-if="!partyBranchHistory || partyBranchHistory.length === 0"
          description="暂无党支部历史记录"
          class="py-8 text-slate-500"
        >
          <template #icon>
            <n-icon :component="TeamIcon" class="text-3xl text-slate-400" />
          </template>
        </n-empty>
        
        <div v-for="(branch, index) in partyBranchHistory" :key="branch.tempId || branch.id || index" class="bg-emerald-50 border border-emerald-200 rounded-xl p-4 mb-3 transition-all duration-300 hover:shadow-md hover:-translate-y-0.5">
          <div class="flex justify-between items-center mb-3">
            <div class="flex items-center gap-3">
              <span class="flex items-center justify-center w-6 h-6 bg-emerald-500 text-white rounded-full text-xs font-semibold">{{ index + 1 }}</span>
              <span v-if="branch.isNew" class="px-2 py-1 bg-green-100 text-green-600 text-xs rounded-full">新增</span>
            </div>
            <div class="flex gap-2">
              <n-button 
                type="primary" 
                @click="savePartyBranchHistory(branch, index)"
                :loading="branchSaveLoading[index]"
                :disabled="!branchChanged[index]"
                class="rounded-lg"
                size="small"
              >
                <template #icon>
                  <n-icon :component="SaveIcon" />
                </template>
                保存
              </n-button>
              <n-button 
                text 
                type="error" 
                @click="deletePartyBranchHistory(branch, index)"
                :loading="branchDeleteLoading[index]"
                class="text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-all duration-300"
                size="small"
              >
                <template #icon>
                  <n-icon :component="DeleteIcon" />
                </template>
                {{ branch.isNew ? '取消' : '删除' }}
              </n-button>
            </div>
          </div>
          <n-grid :cols="12" :x-gap="12" :y-gap="6">
            <n-gi :span="6">
              <n-form-item label="开始时间" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="branch.startDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择开始时间"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="6">
              <n-form-item label="结束时间" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="branch.endDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择结束时间(可为空)"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="4">
              <n-form-item label="单位名称" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="branch.organizationName" 
                  placeholder="请输入单位名称"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="4">
              <n-form-item label="党支部名称" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="branch.branchName" 
                  placeholder="请输入党支部名称"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="4">
              <n-form-item label="担任职务" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="branch.positionHeld" 
                  placeholder="请输入担任职务"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </div>
      </div>
    </n-card>

    <!-- 志愿活动情况卡片 -->
    <n-card class="mb-6 rounded-2xl border-0 shadow-lg bg-white overflow-hidden" title="" :bordered="false">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3 py-2">
            <n-icon class="text-xl text-blue-500" :component="HeartIcon" />
            <span class="text-lg font-semibold text-gray-800">参与相关志愿活动情况</span>
          </div>
          <n-button 
            type="info" 
            @click="addVolunteerActivity"
            class="rounded-lg"
            ghost
          >
            <template #icon>
              <n-icon :component="PlusIcon" />
            </template>
            新增志愿活动
          </n-button>
        </div>
      </template>

      <div class="mb-3">
        <n-empty 
          v-if="!volunteerActivities || volunteerActivities.length === 0"
          description="暂无志愿活动记录"
          class="py-8 text-slate-500"
        >
          <template #icon>
            <n-icon :component="HeartIcon" class="text-3xl text-slate-400" />
          </template>
        </n-empty>
        
        <div v-for="(activity, index) in volunteerActivities" :key="activity.tempId || activity.id || index" class="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-3 transition-all duration-300 hover:shadow-md hover:-translate-y-0.5">
          <div class="flex justify-between items-center mb-3">
            <div class="flex items-center gap-3">
              <span class="flex items-center justify-center w-6 h-6 bg-blue-500 text-white rounded-full text-xs font-semibold">{{ index + 1 }}</span>
              <span v-if="activity.isNew" class="px-2 py-1 bg-green-100 text-green-600 text-xs rounded-full">新增</span>
            </div>
            <div class="flex gap-2">
              <n-button 
                type="info" 
                @click="saveVolunteerActivity(activity, index)"
                :loading="activitySaveLoading[index]"
                :disabled="!activityChanged[index]"
                class="rounded-lg"
                size="small"
              >
                <template #icon>
                  <n-icon :component="SaveIcon" />
                </template>
                保存
              </n-button>
              <n-button 
                text 
                type="error" 
                @click="deleteVolunteerActivity(activity, index)"
                :loading="activityDeleteLoading[index]"
                class="text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-all duration-300"
                size="small"
              >
                <template #icon>
                  <n-icon :component="DeleteIcon" />
                </template>
                {{ activity.isNew ? '取消' : '删除' }}
              </n-button>
            </div>
          </div>
          <n-grid :cols="12" :x-gap="12" :y-gap="6">
            <n-gi :span="4">
              <n-form-item label="活动日期" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="activity.activityDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择活动日期"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="4">
              <n-form-item label="活动名称" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="activity.activityName" 
                  placeholder="请输入活动名称"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="4">
              <n-form-item label="表现情况" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="activity.performanceDesc" 
                  placeholder="请描述表现情况"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </div>
      </div>
    </n-card>

    <!-- 所获奖项卡片 -->
    <n-card class="mb-6 rounded-2xl border-0 shadow-lg bg-white overflow-hidden" title="" :bordered="false">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3 py-2">
            <n-icon class="text-xl text-amber-500" :component="TrophyIcon" />
            <span class="text-lg font-semibold text-gray-800">所获奖项</span>
          </div>
          <n-button 
            type="warning" 
            @click="addAward"
            class="rounded-lg"
            ghost
          >
            <template #icon>
              <n-icon :component="PlusIcon" />
            </template>
            新增奖项
          </n-button>
        </div>
      </template>

      <div class="mb-3">
        <n-empty 
          v-if="!awardsReceived || awardsReceived.length === 0"
          description="暂无获奖记录"
          class="py-8 text-slate-500"
        >
          <template #icon>
            <n-icon :component="TrophyIcon" class="text-3xl text-slate-400" />
          </template>
        </n-empty>
        
        <div v-for="(award, index) in awardsReceived" :key="award.tempId || award.id || index" class="bg-amber-50 border border-amber-200 rounded-xl p-4 mb-3 transition-all duration-300 hover:shadow-md hover:-translate-y-0.5">
          <div class="flex justify-between items-center mb-3">
            <div class="flex items-center gap-3">
              <span class="flex items-center justify-center w-6 h-6 bg-amber-500 text-white rounded-full text-xs font-semibold">{{ index + 1 }}</span>
              <span v-if="award.isNew" class="px-2 py-1 bg-green-100 text-green-600 text-xs rounded-full">新增</span>
            </div>
            <div class="flex gap-2">
              <n-button 
                type="warning" 
                @click="saveAward(award, index)"
                :loading="awardSaveLoading[index]"
                :disabled="!awardChanged[index]"
                class="rounded-lg"
                size="small"
              >
                <template #icon>
                  <n-icon :component="SaveIcon" />
                </template>
                保存
              </n-button>
              <n-button 
                text 
                type="error" 
                @click="deleteAward(award, index)"
                :loading="awardDeleteLoading[index]"
                class="text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-all duration-300"
                size="small"
              >
                <template #icon>
                  <n-icon :component="DeleteIcon" />
                </template>
                {{ award.isNew ? '取消' : '删除' }}
              </n-button>
            </div>
          </div>
          <n-grid :cols="12" :x-gap="12" :y-gap="6">
            <n-gi :span="4">
              <n-form-item label="获奖日期" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="award.awardDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择获奖日期"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="4">
              <n-form-item label="奖项名称" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="award.awardName" 
                  placeholder="请输入奖项名称"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="4">
              <n-form-item label="颁发单位" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="award.issuingAuthority" 
                  placeholder="请输入颁发单位"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, nextTick } from 'vue'
import {
  NForm, NFormItem, NFormItemGi, NGrid, NInput, NDatePicker, NButton, NSelect, NGi, NCard, NIcon, NEmpty
} from 'naive-ui'
import { 
  Person as PersonIcon,
  People as UserIcon,
  BusinessOutline as TeamIcon,
  Heart as HeartIcon,
  Trophy as TrophyIcon,
  Add as PlusIcon,
  TrashOutline as DeleteIcon,
  InformationCircle as InfoIcon,
  Create as EditIcon,
  Save as SaveIcon
} from '@vicons/ionicons5'
import { cloneDeep } from 'lodash-es';

const props = defineProps({
  member: {
    type: Object,
    required: true
  }
})

const emit = defineEmits([
  'save-basic-info',
  'save-party-branch',
  'delete-party-branch',
  'save-volunteer-activity',
  'delete-volunteer-activity',
  'save-award',
  'delete-award'
])

const basicFormRef = ref(null)

// 基本信息
const basicInfo = ref({})
const originalBasicInfo = ref({})
const basicInfoChanged = ref(false)

// 列表数据
const partyBranchHistory = ref([])
const volunteerActivities = ref([])
const awardsReceived = ref([])

// 原始数据副本，用于比较变化
const originalPartyBranch = ref([])
const originalVolunteerActivities = ref([])
const originalAwards = ref([])

// 变化状态
const branchChanged = ref({})
const activityChanged = ref({})
const awardChanged = ref({})

// 加载状态
const basicInfoLoading = ref(false)
const branchSaveLoading = ref({})
const branchDeleteLoading = ref({})
const activitySaveLoading = ref({})
const activityDeleteLoading = ref({})
const awardSaveLoading = ref({})
const awardDeleteLoading = ref({})

// 提示信息配置
const tipMessages = ref([])

// 生成唯一临时ID
const generateTempId = () => {
  return `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 生成提示信息的函数
const generateTipMessages = () => {
  const defaultTips = [
    '测试信息',
    '测试信息', 
    '测试信息',
    '测试信息',
    '测试信息'
  ]
  tipMessages.value = defaultTips
}

// 配置提示信息内容的函数（预留接口）
const configureTipMessages = (messages) => {
  if (Array.isArray(messages)) {
    tipMessages.value = messages
  }
}

// 深度比较对象是否相等
const isEqual = (obj1, obj2) => {
  return JSON.stringify(obj1) === JSON.stringify(obj2)
}

// 初始化数据
const initData = () => {
  if (props.member) {
    // 提取基本信息
    const { partyBranchHistory: pbh, volunteerActivities: va, awardsReceived: ar, ...basicData } = props.member
    basicInfo.value = cloneDeep(basicData)
    originalBasicInfo.value = cloneDeep(basicData)
    
    // 初始化列表数据
    partyBranchHistory.value = cloneDeep(pbh || [])
    volunteerActivities.value = cloneDeep(va || [])
    awardsReceived.value = cloneDeep(ar || [])
    
    // 保存原始数据
    originalPartyBranch.value = cloneDeep(pbh || [])
    originalVolunteerActivities.value = cloneDeep(va || [])
    originalAwards.value = cloneDeep(ar || [])
  }
}

// 监听基本信息变化
watch(basicInfo, (newVal) => {
  basicInfoChanged.value = !isEqual(newVal, originalBasicInfo.value)
}, { deep: true })

// 监听党支部历史变化
watch(partyBranchHistory, (newList) => {
  newList.forEach((item, index) => {
    const original = originalPartyBranch.value.find(orig => orig.id === item.id)
    if (item.isNew || !original) {
      // 新增的记录，检查是否有内容变化
      const emptyItem = {
        startDate: null,
        endDate: null,
        organizationName: '',
        branchName: '',
        positionHeld: ''
      }
      branchChanged.value[index] = !isEqual({
        startDate: item.startDate,
        endDate: item.endDate,
        organizationName: item.organizationName,
        branchName: item.branchName,
        positionHeld: item.positionHeld
      }, emptyItem)
    } else {
      // 现有记录，与原始数据比较
      branchChanged.value[index] = !isEqual({
        startDate: item.startDate,
        endDate: item.endDate,
        organizationName: item.organizationName,
        branchName: item.branchName,
        positionHeld: item.positionHeld
      }, {
        startDate: original.startDate,
        endDate: original.endDate,
        organizationName: original.organizationName,
        branchName: original.branchName,
        positionHeld: original.positionHeld
      })
    }
  })
}, { deep: true })

// 监听志愿活动变化
watch(volunteerActivities, (newList) => {
  newList.forEach((item, index) => {
    const original = originalVolunteerActivities.value.find(orig => orig.id === item.id)
    if (item.isNew || !original) {
      // 新增的记录
      const emptyItem = {
        activityDate: null,
        activityName: '',
        performanceDesc: ''
      }
      activityChanged.value[index] = !isEqual({
        activityDate: item.activityDate,
        activityName: item.activityName,
        performanceDesc: item.performanceDesc
      }, emptyItem)
    } else {
      // 现有记录
      activityChanged.value[index] = !isEqual({
        activityDate: item.activityDate,
        activityName: item.activityName,
        performanceDesc: item.performanceDesc
      }, {
        activityDate: original.activityDate,
        activityName: original.activityName,
        performanceDesc: original.performanceDesc
      })
    }
  })
}, { deep: true })

// 监听所获奖项变化
watch(awardsReceived, (newList) => {
  newList.forEach((item, index) => {
    const original = originalAwards.value.find(orig => orig.id === item.id)
    if (item.isNew || !original) {
      // 新增的记录
      const emptyItem = {
        awardDate: null,
        awardName: '',
        issuingAuthority: ''
      }
      awardChanged.value[index] = !isEqual({
        awardDate: item.awardDate,
        awardName: item.awardName,
        issuingAuthority: item.issuingAuthority
      }, emptyItem)
    } else {
      // 现有记录
      awardChanged.value[index] = !isEqual({
        awardDate: item.awardDate,
        awardName: item.awardName,
        issuingAuthority: item.issuingAuthority
      }, {
        awardDate: original.awardDate,
        awardName: original.awardName,
        issuingAuthority: original.issuingAuthority
      })
    }
  })
}, { deep: true })

onMounted(() => {
  generateTipMessages()
  initData()
})

watch(() => props.member, () => {
  initData()
}, { deep: true })

// =============== 基本信息操作 ===============
const saveBasicInfo = async () => {
  basicInfoLoading.value = true
  try {
    await emit('save-basic-info', cloneDeep(basicInfo.value))
    // 保存成功后更新原始数据
    originalBasicInfo.value = cloneDeep(basicInfo.value)
    basicInfoChanged.value = false
  } finally {
    basicInfoLoading.value = false
  }
}

// =============== 党支部历史操作 ===============
const addPartyBranchHistory = () => {
  const tempId = generateTempId()
  const newBranch = {
    tempId,
    isNew: true,
    startDate: null,
    endDate: null,
    organizationName: '',
    branchName: '',
    positionHeld: ''
  }
  partyBranchHistory.value.unshift(newBranch)
}

const savePartyBranchHistory = async (branch, index) => {
  branchSaveLoading.value[index] = true
  try {
    const branchData = { ...branch }
    delete branchData.tempId
    delete branchData.isNew
    
    if (branch.isNew) {
      await emit('save-party-branch', branchData, -1) // -1 表示新增
    } else {
      await emit('save-party-branch', branchData, index)
    }
    
    // 保存成功后更新状态
    branchChanged.value[index] = false
    if (branch.isNew) {
      branch.isNew = false
      // 如果有id返回，应该设置真实的id
    }
  } finally {
    branchSaveLoading.value[index] = false
  }
}

const deletePartyBranchHistory = async (branch, index) => {
  if (branch.isNew) {
    // 新增的记录直接移除
    partyBranchHistory.value.splice(index, 1)
    return
  }
  
  branchDeleteLoading.value[index] = true
  try {
    await emit('delete-party-branch', branch, index)
    // 删除成功后从列表中移除
    partyBranchHistory.value.splice(index, 1)
  } finally {
    branchDeleteLoading.value[index] = false
  }
}

// =============== 志愿活动操作 ===============
const addVolunteerActivity = () => {
  const tempId = generateTempId()
  const newActivity = {
    tempId,
    isNew: true,
    activityDate: null,
    activityName: '',
    performanceDesc: ''
  }
  volunteerActivities.value.unshift(newActivity)
}

const saveVolunteerActivity = async (activity, index) => {
  activitySaveLoading.value[index] = true
  try {
    const activityData = { ...activity }
    delete activityData.tempId
    delete activityData.isNew
    
    if (activity.isNew) {
      await emit('save-volunteer-activity', activityData, -1) // -1 表示新增
    } else {
      await emit('save-volunteer-activity', activityData, index)
    }
    
    // 保存成功后更新状态
    activityChanged.value[index] = false
    if (activity.isNew) {
      activity.isNew = false
    }
  } finally {
    activitySaveLoading.value[index] = false
  }
}

const deleteVolunteerActivity = async (activity, index) => {
  if (activity.isNew) {
    // 新增的记录直接移除
    volunteerActivities.value.splice(index, 1)
    return
  }
  
  activityDeleteLoading.value[index] = true
  try {
    await emit('delete-volunteer-activity', activity, index)
    // 删除成功后从列表中移除
    volunteerActivities.value.splice(index, 1)
  } finally {
    activityDeleteLoading.value[index] = false
  }
}

// =============== 所获奖项操作 ===============
const addAward = () => {
  const tempId = generateTempId()
  const newAward = {
    tempId,
    isNew: true,
    awardDate: null,
    awardName: '',
    issuingAuthority: ''
  }
  awardsReceived.value.unshift(newAward)
}

const saveAward = async (award, index) => {
  awardSaveLoading.value[index] = true
  try {
    const awardData = { ...award }
    delete awardData.tempId
    delete awardData.isNew
    
    if (award.isNew) {
      await emit('save-award', awardData, -1) // -1 表示新增
    } else {
      await emit('save-award', awardData, index)
    }
    
    // 保存成功后更新状态
    awardChanged.value[index] = false
    if (award.isNew) {
      award.isNew = false
    }
  } finally {
    awardSaveLoading.value[index] = false
  }
}

const deleteAward = async (award, index) => {
  if (award.isNew) {
    // 新增的记录直接移除
    awardsReceived.value.splice(index, 1)
    return
  }
  
  awardDeleteLoading.value[index] = true
  try {
    await emit('delete-award', award, index)
    // 删除成功后从列表中移除
    awardsReceived.value.splice(index, 1)
  } finally {
    awardDeleteLoading.value[index] = false
  }
}

// =============== 数据更新方法（父组件调用） ===============
const updatePartyBranchHistory = (newList) => {
  partyBranchHistory.value = cloneDeep(newList)
  originalPartyBranch.value = cloneDeep(newList)
}

const updateVolunteerActivities = (newList) => {
  volunteerActivities.value = cloneDeep(newList)
  originalVolunteerActivities.value = cloneDeep(newList)
}

const updateAwardsReceived = (newList) => {
  awardsReceived.value = cloneDeep(newList)
  originalAwards.value = cloneDeep(newList)
}

// 获取编辑后的数据，用于保存到后端
const getEditedData = () => {
  // 返回完整的编辑数据，包括基本信息和所有列表数据
  return {
    basicInfo: basicInfo.value,
    partyBranchHistory: partyBranchHistory.value,
    volunteerActivities: volunteerActivities.value,
    awardsReceived: awardsReceived.value
  }
}

defineExpose({
  configureTipMessages,
  updatePartyBranchHistory,
  updateVolunteerActivities,
  updateAwardsReceived,
  getEditedData
})
</script>